package main.leetcode.offer.secondround.from03to50;

import main.datastruc.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/** 34.二叉树中和为某一值的路径 */
public class ex34 {
    private List<List<Integer>> res = new LinkedList<>();

    public static void main(String[] args) {
        TreeNode root = TreeNode.creCmpBTree(new int[] {-2, 0, -3});
        System.out.println(new ex34().pathSum(root, -5));
    }

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        dfs(root, sum, new LinkedList<>());
        return res;
    }

    private void dfs(TreeNode root, int sum, LinkedList<Integer> path) {
        if (root == null /*|| root.val > sum*/) {
            return;
        }
        path.add(root.val);
        // 需要考虑左右节点值为0的情况，还需继续往下
        if (root.val == sum && root.left == null && root.right == null) {
            res.add(new ArrayList<>(path));
        } else {
            dfs(root.left, sum - root.val, path);
            dfs(root.right, sum - root.val, path);
        }
        path.removeLast();
    }
}
